package edenmedical;

import java.io.BufferedReader;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.swtchart.Chart;
import org.swtchart.IAxisTick;
import org.swtchart.ILineSeries;
import org.swtchart.ILineSeries.PlotSymbolType;
import org.swtchart.ISeries.SeriesType;
import org.swtchart.Range;


public class FrmStoricoPulsossimetro implements Listener{
	private Display display;
	private Shell shell;
	private ArrayList<MisuraPulsossimetro> misure;
	private Button btnChiudi;
	private double[] pesiOssigenazione;
	private double[] pesiPulsazioni;
	private Date[] labelDate;
	
	public FrmStoricoPulsossimetro(String dispositivo,DeviceType deviceType){
		misure = new ArrayList<MisuraPulsossimetro>();
		SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		try{
		FileReader os = null;
		switch (deviceType)
		{
			case OMRON:	
				os = new FileReader("data/dbOmron.txt");
				break;
			case SAT300:
				os = new FileReader("data/dbSat300.txt");
				break;
		}
		BufferedReader in = new BufferedReader(os);
		String line;
		while ((line = in.readLine())!=null)
		{
			String[] message = line.split(";");
			misure.add(new MisuraPulsossimetro(format.parse(message[0]),Float.parseFloat(message[1]),Float.parseFloat(message[2])));
		}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}	
		
		this.display = Display.getCurrent();
		shell = new Shell(this.display);
		
		GridLayout gridLayout = new GridLayout();
	    shell.setLayout(gridLayout);
		shell.setText("Storico " + dispositivo);
		gridLayout.numColumns = 1;
		gridLayout.verticalSpacing = 15;
		gridLayout.marginHeight = 20;
		gridLayout.marginWidth = 20;
		
		
		

		Composite dataBar = new Composite(shell, SWT.NONE);
	    dataBar.setLayout(new FillLayout());
	    dataBar.setLayoutData(new GridData(GridData.FILL_BOTH));
	    SashForm sashForm = new SashForm(dataBar, SWT.HORIZONTAL);
	    createContents(sashForm);
	    createPesi();
		createChart(sashForm);
	    sashForm.setWeights(new int[] { 1, 3 });
	    
		btnChiudi = new Button(shell,SWT.PUSH);
		btnChiudi.setText("Chiudi");
		btnChiudi.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
		btnChiudi.addListener(SWT.Selection,this);	
		
	}
	
	private void createContents(Composite composite) {
		  Table table = new Table(composite, SWT.NONE);
		  table.setHeaderVisible(true);
		  table.setLinesVisible(true);
		  TableColumn[] column = new TableColumn[3];
		  column[0] = new TableColumn(table, SWT.NONE);
		  column[0].setText("Data e Ora");
		  
		  column[1] = new TableColumn(table, SWT.NONE);
		  column[1].setText("Ossigenazione");
		  
		  column[2] = new TableColumn(table, SWT.NONE);
		  column[2].setText("Pulsazione");
		  
		  fillTable(table);
		  for (int i = 0, n = column.length; i < n; i++) {
		  column[i].pack();
		  }
	}
		  
	private void fillTable(Table table) {
		  table.setRedraw(false);
		  SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		  for(Iterator<MisuraPulsossimetro> iterator = misure.iterator();iterator.hasNext();){
			  MisuraPulsossimetro mp = (MisuraPulsossimetro) iterator.next();
			  TableItem item = new TableItem(table, SWT.NONE);
			  int c = 0;
			  item.setText(c++, format.format(mp.getData()));
			  item.setText(c++, mp.getOssigenazione().toString());
			  item.setText(c++, mp.getPulsazioni().toString());
		  }
		  
		  table.setRedraw(true);
	}
	
	private void createPesi() {
		int i=0;
		  pesiOssigenazione=new double[misure.size()];
		  pesiPulsazioni=new double[misure.size()];
		  labelDate=new Date[misure.size()];
		  for(Iterator<MisuraPulsossimetro> iterator = misure.iterator();iterator.hasNext();){
			  MisuraPulsossimetro mp = (MisuraPulsossimetro) iterator.next();
			  pesiOssigenazione[i]=mp.getOssigenazione();
			  pesiPulsazioni[i]=mp.getPulsazioni();
			  labelDate[i]=mp.getData();
			  i++;
		  }
	}
	
	public Chart createChart(Composite parent) {

        // create a chart
        Chart chart = new Chart(parent, SWT.NONE);
        
        // set titles
        chart.getTitle().setText("Grafico Misure");
        chart.getAxisSet().getXAxis(0).getTitle().setText("Misure");
        chart.getAxisSet().getYAxis(0).getTitle().setText("Ossigenazione-Pulsazioni");

        // create line series
        ILineSeries lineSeries1 = (ILineSeries) chart.getSeriesSet()
                .createSeries(SeriesType.LINE, "Massima");
        lineSeries1.setYSeries(pesiOssigenazione);
        lineSeries1.setSymbolType(PlotSymbolType.CIRCLE);
        Color red = new Color(display,255,0,0);
        lineSeries1.setSymbolColor(red);
        lineSeries1.setLineColor(red);
        lineSeries1.setXDateSeries(labelDate);
        IAxisTick xTick = chart.getAxisSet().getXAxis(0).getTick();
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        xTick.setFormat(format);

        ILineSeries lineSeries2 = (ILineSeries) chart.getSeriesSet()
        .createSeries(SeriesType.LINE, "Minima");
        lineSeries2.setYSeries(pesiPulsazioni);
        lineSeries2.setXDateSeries(labelDate);
        lineSeries2.setSymbolType(PlotSymbolType.SQUARE);
        Color blue = new Color(display,0,0,255);
        lineSeries2.setSymbolColor(blue);
        lineSeries2.setLineColor(blue);
        
        xTick.setTickLabelAngle(90);
        
        chart.getAxisSet().adjustRange();
        
        Range oldRange = chart.getAxisSet().getYAxes()[0].getRange();
        chart.getAxisSet().getYAxes()[0].setRange(new Range(oldRange.lower-10,oldRange.upper+10));
        
        oldRange = chart.getAxisSet().getXAxes()[0].getRange();
        chart.getAxisSet().getXAxes()[0].setRange(new Range(oldRange.lower-86400000,oldRange.upper+86400000));

        
        return chart;
    }
		
	public void Show(){
		shell.open();
		Monitor primary = display.getPrimaryMonitor();
	    Rectangle bounds = primary.getBounds();
	    Rectangle rect = shell.getBounds();
	    int x = bounds.x + (bounds.width - rect.width) / 2;
	    int y = bounds.y + (bounds.height - rect.height) / 2;
	    shell.setLocation(x, y);
		while( !shell.isDisposed())
		{
			if(!display.readAndDispatch())
				display.sleep();
		}
	}

	public void handleEvent(Event e) {
		if (e.widget.equals(btnChiudi))
		{
			shell.dispose();
		}
	}
}


